package com.example.start

import android.annotation.SuppressLint
import android.content.ContentValues
import android.os.Bundle
import android.provider.BaseColumns
import android.view.MenuItem
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.start.ui.theme.StartTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.IOException
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
import java.net.URL


class WebActivity : AppCompatActivity() {
    val dbHelper = FeedReaderContract.FeedReaderDbHelper(this)
    @SuppressLint("CutPasteId", "SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.web_layout)
        var actionBar = supportActionBar
        actionBar?.title = "网页爬虫"
        actionBar?.setHomeButtonEnabled(true)
        actionBar?.setDisplayHomeAsUpEnabled(true)

        findViewById<Button>(R.id.crawlDataButton).setOnClickListener(
            View.OnClickListener {

                GlobalScope.launch {
                    // 创建一个新的后台线程
                    val html = withContext(Dispatchers.IO) {
                        // 在IO线程中执行网络请求
                        getHtmlContent("https://www.gov.cn/zhengce/zuixin/")
                    }
                    // 网页HTML内容获取成功后，在主线程中进行处理
                    println(html)

                    var document:Document = Document("");
                    var rhtml = html
                    // 在这里处理 HTML 内容
                    document = Jsoup.parse(rhtml)
                    var se = document.getElementsByClass("list list_1 list_2")[0]
                    var ses = se.select("a")
                    for (link in ses) {
                        var urlAddress = link.attribute("href").value
                        if (!urlAddress.contains("https"))
                        {
                            urlAddress = urlAddress.replace("..","https://www.gov.cn/zhengce") + "\n"
                        }
                        addPolicyItem(link.text(),urlAddress)
                        //findViewById<TextView>(R.id.htmlTextView).text = findViewById<TextView>(R.id.htmlTextView).text.toString() + urlAddress
                    }
                    runOnUiThread{
                        Toast.makeText(this@WebActivity, "Found ${ses.count()} items", Toast.LENGTH_SHORT).show()
                    }
                }
                /*
                var document:Document = Document("");
                findViewById<WebView>(R.id.webView1).evaluateJavascript(
                    "(function() { return document.documentElement.innerHTML; })();"
                ) { html ->
                    var rhtml = html.replace("\\u003C","<").replace("\\n","\n")
                        .replace("\\\"","\"")
                    // 在这里处理 HTML 内容
                    document = Jsoup.parse(rhtml)
                    var se = document.getElementsByClass("list list_1 list_2")[0]
                    var ses = se.select("a")
                    for (link in ses) {
                        var urlAddress = link.attribute("href").value
                        if (!urlAddress.contains("https"))
                        {
                            urlAddress = urlAddress.replace("..","https://www.gov.cn/zhengce") + "\n"
                        }
                        addPolicyItem(link.text(),urlAddress)
                        //findViewById<TextView>(R.id.htmlTextView).text = findViewById<TextView>(R.id.htmlTextView).text.toString() + urlAddress
                    }
                    //findViewById<TextView>(R.id.htmlTextView).text = ses[0].html()

                    //findViewById<TextView>(R.id.htmlTextView).text = document.getElementsByAttributeValue("target","_blank")[0].text()

                }
                 */
            }
        )
        val webView: WebView = findViewById(R.id.webView1)
        webView.settings.javaScriptEnabled = true
        // 设置 WebViewClient 来监听页面加载完成事件
        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                // 页面加载完成后获取 HTML 内容
                webView.evaluateJavascript(
                    "(function() { return document.documentElement.outerHTML; })();"
                ) { html ->
                    // 在这里处理 HTML 内容
                    //findViewById<TextView>(R.id.htmlTextView).text = html
                }
            }
        }
        val url = "https://www.gov.cn/zhengce/zuixin/" // 替换为你要加载的网址
        webView.loadUrl(url)

        // 等待协程执行完成
        //Thread.sleep(2000)
    }
    suspend fun getHtmlContent(urlString: String): String {
        return try {
            val url = URL(urlString)
            val connection = url.openConnection()
            connection.connect()

            // 读取网络响应
            val inputStream = connection.getInputStream()
            val content = inputStream.bufferedReader().use { it.readText() }
            content
        } catch (e: Exception) {
            // 处理异常
            e.printStackTrace()
            ""
        }
    }
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId)
        {
            android.R.id.home->
            {
                this.finish()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    val client = OkHttpClient()
    fun getHtml(url: String): String {
        val request = Request.Builder()
            .url(url)
            .build()

        // 发起 HTTP 请求
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) throw IOException("Unexpected code $response")

            // 从响应中读取 HTML 内容
            return response.body!!.string()
        }
    }

    fun addPolicyItem(title : String, url : String)
    {
        // Gets the data repository in write mode
        val db = dbHelper.writableDatabase
        // Create a new map of values, where column names are the keys
        val values = ContentValues().apply {
            put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title)
            put(FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE, url)
        }
        // Insert the new row, returning the primary key value of the new row
        val newRowId = db?.insert(FeedReaderContract.FeedEntry.TABLE_NAME, null, values)
    }
}



@Composable
fun Greeting2(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview2() {
    StartTheme {
        Greeting2("Android")
    }
}